﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;

namespace ARS.Common.Helper
{
    /// <summary>
    /// Json转换类
    /// </summary>
    public static class JsonHelper
    {
        private static readonly JsonSerializerSettings JsonSerializer = new JsonSerializerSettings { DateTimeZoneHandling = DateTimeZoneHandling.Local };

        /// <summary>
        /// Model 转换成Json字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="item"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static string ToJsonString<T>(T item, JsonSerializerSettings settings = null)
        {
            return item == null ? "" : JsonConvert.SerializeObject(item, Formatting.None, settings ?? JsonSerializer);
        }
        /// <summary>
        /// Json字符串 转换成Model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static T JsonToModel<T>(string jsonString, JsonSerializerSettings settings = null)
        {
            if (jsonString is T)
            {
                return (T)Convert.ChangeType(jsonString, typeof(T));
            }
            return string.IsNullOrEmpty(jsonString) ? default(T) : JsonConvert.DeserializeObject<T>(jsonString, settings ?? JsonSerializer);
        }

        private static readonly IsoDateTimeConverter timerConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };

        /// <summary>
        /// Json对象转换成 字符串  Time Format:yyyy-MM-dd HH:mm:ss
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="item"></param>
        /// <returns></returns>
        public static string Tostring<T>(T item)
        {
            return JsonConvert.SerializeObject(item, timerConverter);
        }
    }
}
